package com.example.app;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;

public class Main extends Application {
    private TrayIcon trayIcon;
    @Override
    public void start(Stage stage) {
        WebView webView = new WebView();
        // 可替换为你的业务页面或本地资源
        webView.getEngine().load("http://192.168.0.175:28084/login");

        BorderPane root = new BorderPane(webView);
        Scene scene = new Scene(root, 1024, 768);

        stage.setTitle("成品油");
        stage.setScene(scene);
        stage.setMaximized(true);
        
        // 设置窗口图标
        try {
            // 尝试加载ico格式图标，如果失败则回退到png格式
            try {
                java.net.URL icoUrl = getClass().getResource("/logo.ico");
                if (icoUrl != null) {
                    javafx.scene.image.Image icon = new javafx.scene.image.Image(icoUrl.toExternalForm());
                    stage.getIcons().add(icon);
                } else {
                    // 回退到使用png格式图标
                    System.out.println("无法加载ico图标，回退到png格式");
                    java.net.URL logoUrl = getClass().getResource("/logo.png");
                    if (logoUrl != null) {
                        javafx.scene.image.Image icon = new javafx.scene.image.Image(logoUrl.toExternalForm());
                        stage.getIcons().add(icon);
                    }
                }
            } catch (Exception ex) {
                // 回退到使用png格式图标
                System.out.println("无法加载ico图标，回退到png格式");
                java.net.URL logoUrl = getClass().getResource("/logo.png");
                if (logoUrl != null) {
                    javafx.scene.image.Image icon = new javafx.scene.image.Image(logoUrl.toExternalForm());
                    stage.getIcons().add(icon);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // stage.setFullScreen(true);

        // 托盘运行：关闭窗口时隐藏并保留进程
        Platform.setImplicitExit(false);
        setupSystemTray(stage);
        stage.setOnCloseRequest(event -> {
            event.consume();
            stage.hide();
            // if (trayIcon != null) {
            //     trayIcon.displayMessage("提示", "应用已最小化到托盘", TrayIcon.MessageType.INFO);
            // }
        });

        stage.show();
    }

    private void setupSystemTray(Stage stage) {
        if (!SystemTray.isSupported()) {
            return;
        }
        SystemTray tray = SystemTray.getSystemTray();
        Image image = createTrayImage();

        PopupMenu popup = new PopupMenu();
        MenuItem openItem = new MenuItem("open");
        openItem.addActionListener(e -> Platform.runLater(() -> {
            stage.show();
            stage.toFront();
            stage.setIconified(false);
        }));
        popup.add(openItem);

        trayIcon = new TrayIcon(image, "成品油数据采集器", popup);
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(e -> Platform.runLater(() -> {
            stage.show();
            stage.toFront();
            stage.setIconified(false);
        }));

        try {
            tray.add(trayIcon);
        } catch (AWTException ex) {
            ex.printStackTrace();
        }
    }

    private Image createTrayImage() {
        try {
            // 从resources目录加载logo.png
            java.net.URL logoUrl = getClass().getResource("/logo.png");
            if (logoUrl != null) {
                ImageIcon icon = new ImageIcon(logoUrl);
                // 调整图标大小以适应托盘
                return icon.getImage().getScaledInstance(16, 16, Image.SCALE_SMOOTH);
            } else {
                // 如果无法加载logo.png，创建默认图标
                return createDefaultTrayImage();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return createDefaultTrayImage();
        }
    }
    
    private Image createDefaultTrayImage() {
        int size = 16;
        BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(new Color(0x2D, 0x89, 0xEF));
        g.fillRoundRect(0, 0, size, size, 4, 4);
        g.setColor(Color.WHITE);
        g.setFont(new Font("SansSerif", Font.BOLD, 12));
        String s = "J";
        FontMetrics fm = g.getFontMetrics();
        int x = (size - fm.stringWidth(s)) / 2;
        int y = (size - fm.getHeight()) / 2 + fm.getAscent();
        g.drawString(s, x, y);
        g.dispose();
        return img;
    }

    public static void main(String[] args) {
        
        new Thread(new Heartbeats()).start();
        launch(args);
        

    }
}